﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using JWUX.Supermarket.Model;

namespace JWUX.Supermarket.Utility
{
    public static class JsonSerializer
    {
        /// <summary>
        /// 将T类型序列化为字符串
        /// </summary>
        /// <param name="item">T</param>
        /// <returns></returns>
        public static string Serialize<T>(T item) where T : IJsonSerializable
        {
            return Serialize<T>(item, null);
        }

        /// <summary>
        /// 将T类型序列化为字符串，并且附加至指定文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        /// <param name="fileName">文件名，如果不存在则自动创建</param>
        /// <returns></returns>
        public static string Serialize<T>(T item, string fileName) where T : IJsonSerializable
        {
            if (item == null) return string.Empty;

            var serializer = new DataContractJsonSerializer(item.GetType());

            using (var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, item);

                var sb = new StringBuilder();
                sb.Append(Encoding.UTF8.GetString(ms.ToArray()));

                if (!string.IsNullOrEmpty(fileName))
                {
                    File.AppendAllText(fileName, sb.ToString(), Encoding.UTF8);
                }

                return sb.ToString();
            }
        }

        /// <summary>
        /// 反序列化字符串为T类型
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string jsonString) where T : IJsonSerializable
        {
            if (string.IsNullOrEmpty(jsonString)) return default(T);

            var ser = new DataContractJsonSerializer(typeof(T));

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                T jsonObject = (T)ser.ReadObject(ms);
                return jsonObject;
            }
        }
    }
}
